package com.yejq.http.server;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yejq.util.PropertiesUtils;

public class Server {

	private final static String KEY_PORT = "port";
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@SuppressWarnings("unchecked")
	public void startServer(int port){
		ServerSocket server = null;
		try {
			server = new ServerSocket(port);
			logger.info("server is started..");
			while (true) {
				Socket socket = server.accept();
				logger.info("收到一个请求 马上处理……");
				Class<Processor> clazz = (Class<Processor>)Class.forName(PropertiesUtils.getString("processor"));
				Constructor<Processor> constructor = clazz.getConstructor(Socket.class);
				Processor processor = constructor.newInstance(socket);
				new Thread(processor).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if (server != null) {
					server.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		new Server().startServer(PropertiesUtils.getInt(KEY_PORT));
	}
}
